package com.cssy.yd.logic.web;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONArray;
import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.yd.basic.entity.BasicCompanyDO;
import com.cssy.yd.basic.entity.BasicModePaymentDO;
import com.cssy.yd.basic.service.IBasicCompanyService;
import com.cssy.yd.logic.entity.LogicFkItemDO;
import com.cssy.yd.logic.entity.LogicPoDO;
import com.cssy.yd.logic.entity.LogicPoWareDO;
import com.cssy.yd.logic.entity.LogicFkDO;
import com.cssy.yd.logic.entity.LogicPoWareItemDO;
import com.cssy.yd.logic.entity.LogicSoWareDO;
import com.cssy.yd.logic.entity.LogicSoWareItemDO;
import com.cssy.yd.logic.entity.LogicWhmoveOutwhItemDO;
import com.cssy.yd.logic.service.ILogicFkService;
import com.cssy.yd.logic.service.ILogicPoService;
import com.cssy.yd.logic.service.ILogicPoWareService;
import com.cssy.yd.basic.service.IBasicModePaymentService;
import com.plat.exception.SyBaseException;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.SessionUtil;
import com.plat.util.json.AjaxUtil;
import com.plat.util.json.OutJsonGrid;
import com.yuendong.sy.exception.SyCodeException;

@Controller
@RequestMapping("/yd/logic/fk")
public class FkController extends BaseController<LogicFkDO> {
	private static final Logger logger = Logger.getLogger(FkController.class);
	private static final String MANAGER = "/yd/logic/fk/FKManager";// 列表页面
	private static final String EIDT = "/yd/logic/fk/FkOperation";// 添加、修改、显示页面
	

	
	@Resource(name = "logicFkService")
	private ILogicFkService logicFkService;
	
	@Resource(name = "logicPoWareService")
	private ILogicPoWareService logicPoWareService;
	
	@Resource(name="basicCompanyService")
	private IBasicCompanyService basicCompanyService;
	
	@Resource(name = "basicModePaymentService")
	private IBasicModePaymentService basicModePaymentService;
	
	@Resource(name = "logicPoService")
	private ILogicPoService logicPoService;

	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		return MANAGER;
	}
	
	@Override
	public void list(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JqGridHandler hander=new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		hander.getWheres(scs);
		String spCode =request.getParameter("spCode");
		String pid =request.getParameter("pid");
		if(StringUtils.isNotEmpty(spCode)){
			scs.addCondition("spCode", spCode, SearchCondition.OP_EQUAL);
		}else if(pid!=null&&!"".equals(pid)){
			scs.addCondition("spcode", pid,SearchCondition.OP_EQUAL);
		}
		String billStatus = request.getParameter("billStatus");
		if(StringUtils.isNotEmpty(billStatus)){
			if(StringUtils.equals(billStatus, "0"))
				scs.addCondition("billstatus", Integer.parseInt(billStatus), "=");	
			else
				scs.addCondition("billstatus", Integer.parseInt("0"),"!=");
		}
		
		scs.setOrderBy("dctime desc");
		SearchResult result= logicFkService.findListByExample(scs);
		OutJsonGrid out=new OutJsonGrid(result);
		out.printJSon(response);
	}

	@SuppressWarnings("unchecked")
	@RequestMapping("/fklist")
	@ResponseBody
	public LogicFkDO warelist(HttpServletRequest request, Model model)
			throws Exception {
		String id = request.getParameter("id"); //logic_po_ware.id
		String oricode = request.getParameter("oricode");   //采购入库单号
		String pocode = request.getParameter("pocode");  //采购订单号
		Double yfhk = null;
		Double amount = Double.parseDouble("0.0");		
		
		//设置查询历史退款单的条件
		SearchConditions scs = new SearchConditions();
		scs.addCondition("billstatus", "2", SearchCondition.OP_EQUAL);
		scs.addCondition("oricode", oricode, SearchCondition.OP_EQUAL);
		
		
		List<LogicPoDO> polist = new ArrayList<LogicPoDO>();
		SearchResult sr = new SearchResult();
		SearchConditions scs1 = new SearchConditions();
		scs1.addCondition("pocode", pocode, SearchCondition.OP_EQUAL);
		
		List<LogicPoWareItemDO> powareItem = new ArrayList<LogicPoWareItemDO>();
		LogicFkDO fkDO = new LogicFkDO();
		try{
			powareItem=logicPoWareService.findItemListBypoId(id); //按采购入库单id查询PoWareItemDO
			for(LogicPoWareItemDO poitem : powareItem) {  //遍历采购入库单item得到付款单的总货款
				BigDecimal amount1 = new BigDecimal(poitem.getPrice()==null? new Double("0.0"):poitem.getPrice()).multiply(new BigDecimal(poitem.getJquantity()==null?new Double("0.0"):poitem.getJquantity()));
				amount = new BigDecimal(amount.toString()).add(amount1).doubleValue();
			}
			yfhk = logicFkService.findLastedDOByExample(scs); //最近一次付款后的付款单的已付金额
			sr = logicPoService.findListByExample(scs1);   //根据采购订单编号查询LogicPoDO,以获取币种和汇率
			if(sr.getRecordCount()>0) {
				polist = sr.getResults();
				fkDO.setCurrency(polist.get(0).getCurrency());
				fkDO.setExchangeRate(polist.get(0).getExchangeRate());
			}
			if(yfhk != null&&!"".equals(yfhk) ){
				fkDO.setYfhk(yfhk);
			} else {
				fkDO.setYfhk(Double.parseDouble("0.0"));
			}
			if(amount != null&&!"".equals(amount) ){
				fkDO.setAmount(amount);
			} else {
				fkDO.setAmount(Double.parseDouble("0.0"));
			}
		 } catch(Exception e) {
			 e.printStackTrace();
			 logger.error(e.getMessage(), e);
		 }		
		
		 return fkDO;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping("/fkitemlist")
	public void skitemlist(HttpServletRequest request, HttpServletResponse response, Model model)
			throws Exception {
		String id=request.getParameter("id"); //采购入库单id，等于logic_po_ware_item.powareid，logic_po_ware.id
		String oricode=request.getParameter("oricode");   //采购入库单号
		List<LogicPoWareItemDO> poItem=null;
		List<LogicFkItemDO> fkitem = new ArrayList<LogicFkItemDO>();
		List<LogicFkDO> historyfk = new ArrayList<LogicFkDO>();

		if(id!=null&&!"".equals(id)){
			//按采购入库单id查询采购入库item
			SearchConditions scs1 = new SearchConditions();
			scs1.addCondition("powareid", id, SearchCondition.OP_EQUAL);
			scs1.setRemovedProperty(null);
			scs1.setLimitPage(false);
			scs1.setOrderBy("code");
			poItem=logicPoWareService.findItemListByExample(scs1).getResults();
		}
		
		if(oricode!=null&&!"".equals(oricode)) {	
			SearchConditions scs = new SearchConditions();
			SearchResult sr = new SearchResult();
			scs.addCondition("oricode", oricode, SearchCondition.OP_EQUAL);
			scs.addCondition("billstatus","2", SearchCondition.OP_EQUAL);
			//查找对应的所有历史付款单 按采购入库单(oricode)及单据状态为完结的(billstatus=2)来查
			sr = logicFkService.findListByExample(scs);
			if(sr.getRecordCount()>0){ //有付款记录
				historyfk = sr.getResults();
				for (LogicPoWareItemDO si : poItem) {
					BigDecimal tempyfhk = new BigDecimal("0.0");
					Double yfhk = Double.parseDouble("0.0");
					Double wfhk = Double.parseDouble("0.0");
					LogicFkItemDO li = new LogicFkItemDO();
	//				li.setBatch(si.getBatch());
					li.setCode(si.getCode());
					li.setName(si.getName());
	//				li.setStatus(si.getState());
					li.setUnit(si.getJunit());
					li.setSpec(si.getSpec());
					li.setQuantity(si.getJquantity());
					li.setTax_price(new BigDecimal(si.getPrice()==null? new Double("0.0"):si.getPrice()));
					li.setAmount(new BigDecimal(si.getPrice()==null? new Double("0.0"):si.getPrice()).multiply(new BigDecimal(si.getJquantity()==null?new Double("0.0"):si.getJquantity())).doubleValue());			
					for(LogicFkDO hisfk : historyfk) { //历史付款单循环
						SearchConditions scs1 = new SearchConditions();
						SearchResult sr1 = new SearchResult();
						scs1.setRemovedProperty(null);
						scs1.addCondition("fkid", hisfk.getId(), SearchCondition.OP_EQUAL);
		//				scs1.addCondition("batch", li.getBatch(), SearchCondition.OP_EQUAL);
						scs1.addCondition("code",li.getCode(), SearchCondition.OP_EQUAL); 
		//				scs1.addCondition("status",li.getStatus(), SearchCondition.OP_EQUAL); 
						sr1 = logicFkService.findItemListByExample(scs1);  //查找此物料的历史收款记录
						if(sr1.getRecordCount()>0){
							List<LogicFkItemDO> hislist = sr1.getResults();
							LogicFkItemDO hisitemdo = hislist.get(0);
							tempyfhk = tempyfhk.add(new BigDecimal(hisitemdo.getSfhk().toString())); 
							wfhk = new BigDecimal(li.getAmount().toString()).subtract(tempyfhk).doubleValue();
							yfhk = tempyfhk.doubleValue();
						}else if(sr1.getRecordCount()==0){
							wfhk = new BigDecimal(li.getAmount().toString()).subtract(tempyfhk).doubleValue();
							yfhk = tempyfhk.doubleValue();
						}
					}
					li.setYfhk(yfhk);
					li.setWfhk(wfhk);
					li.setSfhk(Double.parseDouble("0.0"));
					fkitem.add(li);
				}
				
			 }else { //没有历史付款记录，第一次新增付款单
				for (LogicPoWareItemDO si : poItem) {
					LogicFkItemDO li = new LogicFkItemDO();
		//			li.setBatch(si.getBatch());
					li.setCode(si.getCode());
					li.setName(si.getName());
		//			li.setStatus(si.getState());
					li.setUnit(si.getJunit());
					li.setSpec(si.getSpec());
					li.setQuantity(si.getJquantity());
					li.setTax_price(new BigDecimal(si.getPrice()==null? new Double("0.0"):si.getPrice()));
					li.setAmount(new BigDecimal(si.getPrice()==null? new Double("0.0"):si.getPrice()).multiply(new BigDecimal(si.getJquantity()==null?new Double("0.0"):si.getJquantity())).doubleValue());
					li.setYfhk(Double.parseDouble("0.0"));
					li.setSfhk(Double.parseDouble("0.0"));
					li.setWfhk(li.getAmount());
					fkitem.add(li);
				}
			}
		}
		SearchResult result =new SearchResult();
		result.setResults(fkitem);
		result.setRecordCount(fkitem.size());
		OutJsonGrid out=new OutJsonGrid(result);
		out.printJSon(response);
	}

	@SuppressWarnings("unchecked")
	@Override
	public String operationForm(HttpServletRequest request,
			@PathVariable String id, @PathVariable String flag, Model model)
			throws Exception {
		/*SearchConditions scs1 = new SearchConditions();
		scs1.addCondition("parentname", "供应商",SearchCondition.OP_EQUAL);
		scs1.setOrderBy("code");
		List<BasicCompanyDO> companyDOs = basicCompanyService.findListByExample(scs1).getResults();  */
		if (OperationFlag.ADD.equals(flag)) {// 新增单据时操作
			model.addAttribute("flag", "ADD");
			SearchConditions scs = new SearchConditions();
			scs.setOrderBy("dctime desc");
			scs.addCondition("spcode", id, SearchCondition.OP_EQUAL);
			scs.addCondition("fkstatus", "0,1", SearchCondition.OP_IN);
			scs.addCondition("billstatus", "3,4,5", SearchCondition.OP_IN);  //采购入库单据状态 3为完成,4为部分退货,5为全部退货
			SearchResult sr = logicPoWareService.findListByExample(scs);
			List<LogicPoWareDO> lpwd= sr.getResults();
			 model.addAttribute("powarelist", lpwd);
			 model.addAttribute("xx", 1);
			 model.addAttribute("pid", id);
			 
			 //查询付款方式
			 SearchConditions scs2 = new SearchConditions();
			 scs2.setRemovedProperty(null);
			 SearchResult result1 = basicModePaymentService.findListByExample(scs2);
			 List<BasicModePaymentDO> mp = result1.getResults();
			 model.addAttribute("payment", mp);
		} else {
			LogicFkDO lpd =logicFkService.findListById(id);
			//List<LogicFkItemDO> fkitemlist=logicFkService.findItemListByfkid(lpd.getId());
			model.addAttribute("fk", lpd);
			model.addAttribute("flag", lpd.getBillStatus());
			//model.addAttribute("fkitemlist", fkitemlist);
			model.addAttribute("pid", lpd.getSpCode());
			
			if(lpd.getBillStatus()==0){
				 //查询付款方式
				 SearchConditions scs2 = new SearchConditions();
				 scs2.setRemovedProperty(null);
				 SearchResult result = basicModePaymentService.findListByExample(scs2);
				 List<BasicModePaymentDO> mp = result.getResults();
				 model.addAttribute("payment", mp);
				 model.addAttribute("xx", 1);
			 }
		}
	//	model.addAttribute("companyDOs", companyDOs);
		return EIDT;
	}
	
	
	@RequestMapping("/griditems")
	public void griditems(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			LogicFkDO lpd =logicFkService.findListById(id);
			List<LogicFkItemDO> fkitemlist=logicFkService.findItemListByfkid(lpd.getId());
			OutJsonGrid out = new OutJsonGrid(fkitemlist);
			out.printJSon(response);
		}
	}

	@Override
	public Map<String, Object> save(HttpServletRequest request,
			LogicFkDO curAP, BindingResult result, Model model) throws SyBaseException, SyCodeException {
		BodyMsg bodyMap = BodyMsg.getInstance();
		String itemdata =request.getParameter("itemdata");
		String submitFlag = request.getParameter("submitFlag");
		if(itemdata==null&&"".equals(itemdata)){
			bodyMap.isFail();
			bodyMap.configWebInfor("付款单内容不能为空！");
			return bodyMap.modelMap;
		}
		try {
			if("0".equals(submitFlag)){
				curAP.setBillStatus(0);
				curAP.setFkStatus(0);
				logicFkService.fksave(request, curAP);
			}
			if("1".equals(submitFlag)){
				curAP.setBillStatus(2);
				logicFkService.fkcommit(request, curAP);
			}
			
			bodyMap.isSuccess();
			bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
			bodyMap.configWebId(curAP.getId());
		} catch (Exception e) {
			e.printStackTrace();
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
		return bodyMap.modelMap;
	}
	

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String ids = request.getParameter("ids");
			String[] fields=ids.split(",");
			for(String field : fields){
				LogicFkDO ld=logicFkService.findListById(field);
				if(ld.getId()!=null){
					ld.setRemoved(1);
					logicFkService.update(ld,SessionUtil.getUser(request));
				}
			}
			bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
		} catch (Exception e) {
			e.printStackTrace();
			bodyMap.isFail(GlobalResLoader.getOpfailed() + e.getMessage());
		}
		return bodyMap.modelMap;
	}

	/**
	 * ligerUI树的json
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/tree")
	public void treelist(HttpServletRequest request,HttpServletResponse response)throws Exception{
		JqGridHandler hander=new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		scs.setLimitPage(false);//不分页
		hander.getWheresNotLimit(scs);
		List<BasicCompanyDO> list =basicCompanyService.find(scs);
		AjaxUtil.printJSonArr(response, JSONArray.toJSONString(list));
	}
	
	@RequestMapping(value = "/exportExcel")
	public void printer(HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		try {
			
			String id = request.getParameter("id");
			LogicFkDO fkdo = new LogicFkDO();
			List<LogicFkItemDO> lp = new ArrayList<LogicFkItemDO>();
			if(!"".equals(id)&&id!=null){
				fkdo = logicFkService.findListById(id);
			}
			if(fkdo.getId()!=null){
				lp = logicFkService.findItemListByfkid(fkdo.getId());
			}
				request.setAttribute("fk", fkdo);
				request.setAttribute("lp", lp);
				
				response.setContentType("application/vnd.ms-excel");
				response.setHeader("Content-disposition", "attachment;filename=" + fkdo.getFkCode() + ".xls");
			
				RequestDispatcher dispatcher = request.getRequestDispatcher("/views/printer/FkPrint.jsp");
			
				dispatcher.forward(request, response);
			
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}